<template>
  <div class="work_sheet_manage">
    <one-title title="生产调度工作台" @refreshData="refresh">
      <div class="mes_btn">
        <el-button
          v-btn-permission="'weeklyPlanBoard'"
          type="primary" @click="weeklyPlanBoard">
          <i class="iconfont icon-td_check"></i>
          周计划看板
        </el-button>
        <disabled-btn
          v-btn-permission="'batchCreate'"
          :judge="createBtnStatus"
          iconClass="iconfont icon-btn_addnew"
          btnText="周转批次创建"
          btnType="success"
          @judgeClick="wakeBatchCreate"></disabled-btn>
      </div>
    </one-title>
    <div class="task_tree_container">
      <task-bom-tree ref="taskBomTree" @selectNode="selectNode"></task-bom-tree>
      <div class="task_tree_content">
        <mes-search-comp
          :searchList="tableColConfig"
          :searchResult="searchResult"
          ref="mesSearchs"
          :showSlotSet="true"
          :showSlotExport="true"
          @setCol="$refs.ColumnControl.openDialog()"
          @searchInfo="_info"
          @exportTable="_exportTable">
        </mes-search-comp>
        <!--生产调度列表-->
        <div class="table_container">
          <el-table
            ref="tableNode"
            border
            stripe
            v-loading="isLoading"
            style="width: 100%"
            :data="listData.list"
            :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
            @row-click="(row) => $refs.tableNode.toggleRowSelection(row)"
            @sort-change="_sort"
            @selection-change="handleSelectionChange"
            @filter-change="handleFilterChange">
            <el-table-column
              fixed="left"
              align="center"
              type="selection"
              :disabled="true"
              width="40">
            </el-table-column>
            <mes-col-comp
              :key="index"
              v-for="(column, index) in columnList"
              :column="column">
            </mes-col-comp>
            <el-table-column
              fixed="right"
              :resizable="false"
              min-width="90"
              label="操作"
              align="center">
              <template slot-scope="scope">
                <span class="jump_item" @click.stop="showLog(scope.row)">操作记录</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <mes-pagination
          @updateData="init"
          :currentPage="listData.pageNo"
          :total="listData.count || 0"
          :pageSize="listData.pageSize"
          :pageSelectShow="false">
        </mes-pagination>
        <!--工单预拆分-->
        <batch-create
          ref="batchCreate"
          :intoData="insertCreateData"
          @createSuccess="createSuccess">
        </batch-create>
        <!--拆分结果确认-->
        <split-preview
          ref="splitPreview"
          @closePage="switchDialods('closeAll')"
          @goBackPrev="switchDialods('goBackPrev')"
          :listData="splitPreviewList"
          @splitSuccess="splitSuccess">
        </split-preview>
        <!--周转批次清单-->
        <batch-list ref="batchList" @cancelBatch="init()"></batch-list>
      </div>
    </div>
    <!--周计划看板-->
    <weekly-plan ref="weeklyPlan" @submitSuccess="init"></weekly-plan>
    <!-- 日志详情 -->
    <log-detail ref="logDetail"></log-detail>
    <!--列隐藏 -->
    <column-control ref="ColumnControl" :colList="tableColConfig" @saveCol="saveCol"></column-control>
  </div>
</template>

<script>
import {BatchCreate, BatchList, SplitPreview, WeeklyPlan} from './components'
import tableColConfig from './components/workOrderColumn'

export default {
  name: 'WorkSheetManage',
  components: {
    BatchCreate,
    BatchList,
    SplitPreview,
    WeeklyPlan
  },
  data() {
    return {
      isLoading: false, // 数据加载中
      editState: true, // 修改按钮是否禁用
      selectData: [], // 选中的表格数据
      searchData: {}, // 搜索列表数据
      sortData: {}, // 排序字段
      insertCreateData: [], // 预拆分所需数据
      outputCreateData: [], // 返回的预拆分请求数据
      splitPreviewShow: false, // 是否加载工单拆分预览组件
      // 拆分预览初始列表
      splitPreviewList: {
        workorderList: [],
        turnoverBatchList: [],
        workorderWorkstageList: []
      },
      searchResult: NaN, // 搜索结果数
      taskNumber: '', // 当前树形taskNumber
      workorderIds: [], // 当前树形工单ids
      checkedKeys: window.localStorage.getItem(this.$route.name), // 显示的列集合
      selectReocrd: false, // 工单列表勾选记录
    }
  },
  computed: {
    // 列表数据
    listData() {
      return this.$store.state.workSheetManage.listData
    },
    // 周转状态列表
    processStatus() {
      let list = this.$store.state.dict.workorderProcessStatus.labels || []
      return list.filter(item => item.value !== 'ToBeAssigned' && item.value !== 'ToBeConfirmed') || []
    },
    // 进度状态初始查询条件
    processStatusIds() {
      return this.processStatus.reduce((pre, cur) => [...pre, cur.id], []).join(',')
    },
    tableColConfig,
    // 列循环
    columnList() {
      this.$nextTick(() => {
        this.$refs.tableNode.doLayout()
      })
      let checkedKeysList = this.checkedKeys ? JSON.parse(this.checkedKeys) : this.tableColConfig.reduce((pre, cur) => [...pre, cur.prop], [])
      return this.tableColConfig.filter(item => item.noForCol !== true && (item.noChecked === true || checkedKeysList.some(key => key === item.prop)))
    },
    // 验证是否已选
    _selected() {
      if (!this.selectData.length) return {msg: '请选择一条工单！'}
    },
    // 批次创建按钮状态
    createBtnStatus() {
      if (this._selected) return this._selected
      let status = false
      const msg = '请选择工单状态为"正常", 工单状态为"待拆分"或"部分拆分"的工单进行拆分'
      if (this.selectData.find((item) => item.statusValue !== 'Normal') || this.selectData.find((item) => item.workorderProcessStatusValue === 'CompleteSplitted' || item.workorderProcessStatusValue === 'Finished')) {
        status = true
      }
      return status ? {disabled: status, msg: msg} : {msg: false}
    },
  },
  mounted() {
    this.$refs.taskBomTree.init()
    this.init()
    this.getNameTree()
  },
  methods: {
    // 列筛选回调
    handleFilterChange(filters) {
      this.sortData = {}
      this.$refs.tableNode.clearSort()
      let filterParams = this.$filterParams(this.tableColConfig, filters)
      Object.assign(this.searchData, filterParams.search)
      Object.assign(this.sortData, filterParams.order)
      this.init()
    },
    // 修改列显示
    saveCol(checkedKeys) {
      this.checkedKeys = checkedKeys
    },
    // 刷新方法
    refresh() {
      this.taskNumber = ''
      if (!this.selectData.length) {
        this.$refs.batchList.refresh()
      }
      this.$refs.mesSearchs.clean()
      this.searchData = {}
      this.sortData = {}
      this.$refs.tableNode.clearSort()
      this.$refs.tableNode.clearFilter()
      this.selectData = []
      this.outputCreateData = []
      this.workorderIds = []
      this.$refs.taskBomTree.init()
      this.init()
    },
    // 选择树形节点
    selectNode(taskNumber, workorderIds) {
      this.taskNumber = taskNumber
      this.workorderIds = workorderIds
      if (!this.selectData.length) {
        this.getBatchList()
      }
      this.outputCreateData = []
      this.searchData = {}
      this.selectData = []
      this.init()
    },
    // 导出表格
    _exportTable() {
      let postData = this.getPostData({
        pageNo: 1,
        pageSize: 9999999
      })
      this.$exportTable(postData, 'a/workorder/workorder/exportasexcel', '调度工单')
    },
    // 获取请求数据
    getPostData(page) {
      let postData = {
        pageNo: page ? page.pageNo : 1,
        pageSize: page ? page.pageSize : 5,
        sort: this.sortData,
        query: {
          columns: this.tableColConfig.reduce((pre, cur) => [...pre, cur.prop], []),
          ...this.searchData,
          viewSource: 3
        } // viewSource 视图来源，3表示生产调度工单
      }
      if (!postData.query.workorderProcessStatusId) {
        postData.query.workorderProcessStatusId = this.processStatusIds
      }
      if (this.taskNumber) {
        postData.query.taskNumber = this.taskNumber
      }
      if (this.workorderIds.length) {
        postData.query.id = this.workorderIds.toString()
      }
      return postData
    },
    // 初始化列表数据
    init(page) {
      this.isLoading = true
      let postData = this.getPostData(page)
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workorder/workorder/list',
        data: postData,
        module: 'workSheetManage',
        state: 'listData'
      }).then((res) => {
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
      }).then(() => {
        this.setTableSelect(this.listData.list, this.outputCreateData)
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 显示日志
    showLog(row) {
      this.$refs.logDetail.openDialog({
        title: '工单编号',
        name: row.number,
        url: 'a/workorderstatuschangehistory/workorderStatusChangeHistory/list',
        query: {
          workorderId: row.id
        }
      })
    },
    // 编辑
    _edit() {
      if (this.selectData.length === 1) {
        this.$router.push({
          name: 'workListReceiveDetail',
          params: {
            id: this.selectData[0].id
          }
        })
      }
    },
    // 查询
    _info(data) {
      this.searchData = data
      this.$refs.tableNode.clearSort()
      this.sortData = {}
      this.$refs.tableNode.clearFilter()
      this.init()
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    // 调度列表勾选
    handleSelectionChange(val) {
      this.selectData = val
      if (val.length) {
        this.selectReocrd = true
        this.outputCreateData = val
      }
      if (this.selectReocrd) {
        this.getBatchList()
      }
    },
    /**
     * 设置调度列表勾选--拆分成功后将调度主列表所选项回填
     * @param data 调度列表数据
     * @param list 所勾选的调度数据
     */
    setTableSelect(data, list) {
      if (list && list.length) {
        this.selectData = list
      }
      if (Array.isArray(data) && data.length) {
        data.forEach(item => {
          if (list.some((value) => value.id === item.id)) {
            this.$refs.tableNode.toggleRowSelection(item, true)
          }
        })
      }
    },
    // 开启预拆分组件
    wakeBatchCreate() {
      this.$refs.batchCreate.switchDialog(true)
      this.insertCreateData = JSON.parse(JSON.stringify(this.selectData))
    },
    /**
     * dialog弹窗组件开启、关闭控制
     * @param value 弹框控制参数
     */
    switchDialods(value) {
      switch (value) {
        // 关闭所有dialog组件弹窗
        case 'closeAll':
          this.$refs.batchCreate.switchDialog(false)
          this.$refs.splitPreview.switchDialog(false)
          break
        // 预览页面返回上一页重新开启拆分弹窗、关闭预览弹窗
        case 'goBackPrev':
          this.$refs.batchCreate.switchDialog(true)
          this.$refs.splitPreview.switchDialog(false)
          break
      }
    },
    /**
     * 预拆分批次创建成功
     * @param obj 预拆分批次创建数据: 初始数据(sourceData)/请求数据(createData)/响应(response)数据
     */
    createSuccess(obj) {
      this.outputCreateData = obj.sourceData
      let createData = obj.createData
      let response = obj.response
      let workorderList = response.workorderList || []
      workorderList.forEach((item) => {
        let matchItem = createData.find((value) => value.workorderId === item.id)
        if (matchItem) {
          item.splitNumber = matchItem.splitNumber
          item.turnoverNumber = matchItem.TurnoverNumber
        }
      })
      // 获取"下一步"预拆分弹窗所需要的数据
      this.splitPreviewList = response
      setTimeout(() => {
        this.$refs.splitPreview.switchDialog(true)
      }, 400)
    },
    // 拆分成功
    splitSuccess() {
      this.switchDialods('closeAll')
      this.init()
      this.selectReocrd = false
    },
    // 批次清单列表获取
    getBatchList() {
      let workeroderMsg = this.taskNumber || this.workorderIds
      if (this.selectData.length) {
        let ids = this.selectData.reduce((pre, cur) => [...pre, cur.id], []).join(',')
        this.$refs.batchList.showBatchList(ids, workeroderMsg)
      } else {
        this.$refs.batchList.refresh(workeroderMsg)
      }
    },
    // 周计划看板
    weeklyPlanBoard() {
      this.$refs.weeklyPlan.openDialog()
    },
    // 获取班组、工作中心树形;为生产调度、工序拆分做准备
    getNameTree() {
      this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/workgroup/workgroup/nametree',
        module: 'workSheetManage',
        state: 'treeList'
      })
    },
    /**
     * 提示
     * @param type 提示类型
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .work_sheet_manage {
    height: 100%;
    .state_icon_word {
      padding-left: 3px;
    }
    .err_msg {
      .el-table__header-wrapper {
        display: none;
      }
      .el-table td {
        padding: 0;
        height: 30px;
        line-height: 30px;
      }
    }
  }
</style>
